﻿using Sustainalytics.CDDB.DataConnector;
using Sustainalytics.ClientDW.Synchronization.SyncRiskRatingsData.CorporateDataLogic;
using Sustainalytics.SharedEntities.Corporate;
using Sustainalytics.SharedEntities.Interfaces.Enums;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace Sustainalytics.ClientDW.Synchronization.SyncRiskRatingsData
{
    public static class CoreRiskRatingCorporateDataQuery
    {
        public static IEnumerable<RiskRatingCorporateData> Get(CorporateDataRepository cddb)
        {
            return cddb.ListCompaniesWithActiveResearch(ResearchFramework.CoreRiskRatings,
                new List<Expression<Func<CorporateDetails, string>>>
                {
                    cd => nameof(cd.Country),
                    cd => nameof(cd.CompanyName),
                    cd => nameof(cd.MainIdentifiers.ExchangeTicker),
                    cd => nameof(cd.SubPeerGroupId),
                    cd => nameof(cd.SubPeerGroup),
                    cd => nameof(cd.PeerGroup),
                    cd => nameof(cd.MarketCapitalization)
                })
                .Where(x => !x.ResearchParentId.HasValue)
                .Select(cd =>
                {
                    var mainExchangeTicker = cd.MainIdentifiers.ExchangeTicker;
                    var mainExchangeTickerSegments = mainExchangeTicker?.Split(':');

                    return new RiskRatingCorporateData
                    {
                        CompanyId = cd.Id,
                        CompanyName = cd.CompanyName,
                        Country = cd.Country,
                        ExchangeTicker = mainExchangeTicker,
                        Exchange = mainExchangeTickerSegments?.Length == 2 ? mainExchangeTickerSegments[0] : null,
                        Ticker = mainExchangeTickerSegments?.Length == 2 ? mainExchangeTickerSegments[1] : null,
                        SubPeerGroupId = cd.SubPeerGroupId,
                        SubPeerGroup = cd.SubPeerGroup,
                        PeerGroup = cd.PeerGroup,
                        MarketCapitalization = cd.MarketCapitalization
                    };
                });
        }
    }
}
